/* 
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include "cookiestorage.h"
#include "paths.h"
#include "log.h"

namespace Wishmaster
{
	CookieStorage::CookieStorage()
	{
	}

	CookieStorage::~CookieStorage()
	{
	}

	bool CookieStorage::save(const QString& destination)
	{
		QString result;
		for(DomainMap::iterator it = m_domains.begin(); it != m_domains.end(); ++it)
		{
			result += QString("[%1]\n").arg(it.key());
			result += saveStringMap(it.value());
		}
		QFile f(DefaultPath::storageRoot() + QDir::separator() + destination);
		if(!f.open(QIODevice::WriteOnly | QIODevice::Text))
		{
			log(llError, "Unable to save cookies to file: %s", qPrintable(f.fileName()));
			return false;
		}
		f.write(result.toUtf8());
		f.close();
		return true;
	}

	QString CookieStorage::saveStringMap(const StringMap& map)
	{
		QString result;
		for(StringMap::const_iterator it = map.begin(); it != map.end(); ++it)
		{
			result.append(QString("%1=%2\n").arg(it.key()).arg(it.value()));
		}
		return result;
	}

	bool CookieStorage::load(const QString& source)
	{
		QFile f(DefaultPath::storageRoot() + QDir::separator() + source);
		if(!f.open(QIODevice::ReadOnly | QIODevice::Text))
			return false;
		QString domain;
		StringMap map;
		while(!f.atEnd())
		{
			QString line = QString::fromUtf8(f.readLine()).trimmed();
			if(line.startsWith('['))
			{
				if(!domain.isEmpty())
				{
					m_domains.insert(domain, map);
					map = StringMap();
				}
				domain = line.mid(1, line.size() - 2);
			}
			else
			{
				if(domain.isEmpty())
					continue;
				if(line.count('=') == 0)
					continue;
				map.insert(line.section('=', 0, 0), line.section('=', 1));
			}
		}
		m_domains.insert(domain, map);
		return true;
	}

	QStringList CookieStorage::cookiesForDomain(const QString& domain)
	{
		DomainMap::iterator it = m_domains.find(domain);
		if(it == m_domains.end())
			return QStringList();
		return it.value().keys();
	}

	QString CookieStorage::cookieString(const QString& domain)
	{
		QString result;
		QStringList cookies = cookiesForDomain(domain);
		bool first = true;
		foreach(const QString& c, cookies)
		{
			if(!first)
				result += "; ";
			first = false;
			result += QString("%1=%2").arg(c, cookie(domain, c));
		}
		return result;
	}

	QString CookieStorage::cookie(const QString& domain, const QString& key)
	{
		DomainMap::iterator it = m_domains.find(domain);
		if(it == m_domains.end())
			return QString::null;
		StringMap::iterator cit = it.value().find(key);
		if(cit == it.value().end())
			return QString::null;
		return cit.value();
	}

	void CookieStorage::setCookie(const QString& domain, const QString& key, const QString& value)
	{
		m_domains[domain][key] = value;
	}

	void CookieStorage::setCookieString(const QString& domain, const QString& string)
	{
		log(llDebug, "Cookie string for domain %s: %s", qPrintable(domain), qPrintable(string));
		QStringList sections = string.split(';', QString::SkipEmptyParts);
		foreach(const QString& section, sections)
		{
			QString key = section.section('=', 0, 0).trimmed();
			QString value = section.section('=', 1).trimmed();
			if(key.compare("expires", Qt::CaseInsensitive) == 0 ||
					key.compare("path", Qt::CaseInsensitive) == 0)
				continue;
			m_domains[domain][key] = value;
		}
	}
}

